// pages/chat/index.js
var websocket=require("../../utils/websocket")
//获取应用实例
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
      userid:"",
      username: "",
      userimg:"",
      scrollTop:"",
      scrollIntoView:"",
      send:"",
      count:0,
      list: [],
  },
  onLoad: function () {
    //连接socket
    websocket.connect()
    var that = this
     //用户进入聊天室
    app.getUserInfo(function (userInfo) {
      var userid = websocket.userid();
      var msg = '{"type":"userlogin","userid":"' + userid+'","userimg":"' + userInfo.avatarUrl + '","username":"' + userInfo.nickName + '"}'
      that.setData({
        username: userInfo.nickName,
        userimg: userInfo.avatarUrl,
        userid: userid
      })
      websocket.send(msg);
    })
    //用户接受信息
    wx.onSocketMessage(function (res) {
      var data = JSON.parse(res.data);
      var ty = data.type;
      var d = that.data.list
      if (ty == "login") {
        var msg = { username: data.username, msg: data.msg, type: "userlogin" };
      }
      if (ty == "say") {
        var msg = { userimg: data.userimg, msg: data.msg, type: "say" };
      }
      if (ty == "close") {
        var msg = { username: data.username, msg: data.msg, type: "close" };
      }
      if (d == null) {
        var list = [msg]
      } else {
        var list = that.data.list.concat(msg)
      }
      that.setData({
        list: list,
        send:"",
        count: data.count
      })
    })
    
    //关闭socket  
    wx.onSocketClose(function(res){
      var msg = '{"type":"close","username":"' + that.data.username + '"}'
      websocket.send(msg);
    })
    //心跳包
    setInterval(function () {
      var msg = '{"type":"online","userid":"' + that.data.userid + '"}'
      websocket.send(msg);
    }, 3000)
  },
  //用户发送信息
  formSubmit:function(e){
    var msg = e.detail.value['send'];
    if(msg!=""){
      //发送信息
      var msg = '{"type":"say","userimg":"' + this.data.userimg + '","msg":"' + msg + '"}'
      websocket.send(msg);
    }
  },
  
})
